<?php
// +----------------------------------------------------------------------
// | Desc: [ Better-卡分组 ]
// +----------------------------------------------------------------------
// | Author: huangzhen_20210406
// +----------------------------------------------------------------------

namespace app\common\model;

use app\api\controller\Index as apiIndex;
use think\facade\Db;
use app\api\controller\EmailSend;

class UserCheck extends Common
{
    /**
     * 返回layui的table所需要的格式
     * @param $post
     * @param $user_id
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function tableData($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        if(isset($post['username']) && !empty($post['username'])){
            $where[] = ['username', 'like', '%'.$post['username'].'%'];
        }
        if(isset($post['check_status']) && strlen($post['check_status']) >0){
            $where[] = ['check_status', '=', $post['check_status']];
        }
        if(isset($post['active_type']) && strlen($post['active_type']) >0){
            if($post['active_type'] == 0){
                $where[] = ['parent_id', '=', 0];
            }else{
                $where[] = ['parent_id', '<>', 0];
            }
        }

        if(isset($post['company_name']) && !empty($post['company_name'])){
            $where[] = ['applicant', 'like', '%'.$post['company_name'].'%'];
        }
        if(isset($post['business_token']) && !empty($post['business_token'])){
            $where[] = ['business_token', 'like', '%'.$post['business_token'].'%'];
        }

        $list = Db::name('user_check')
                ->where($where)
                ->order('ctime desc')
                ->field('id,username,check_status,check_result,check_kyc,ctime,business_token,applicant,parent_id')
                ->paginate(['list_rows' => $list_rows, 'page' => $page])
                ->toArray();
        if(isset($list['data']) && count($list['data']) >0){
            foreach ($list['data'] as &$v){
                $applicant      = $v['applicant'];
                $applicant_json = json_decode($applicant , true);
                $v['name']   = $applicant_json['first_name'] . ' ' . $applicant_json['last_name'];
                $v['company_name'] = $applicant_json['company_name'];
            }
        }
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    public function updateCheckStatus($post)
    {
        $check_id       = $post['check_id'];
        $check_status   = $post['check_status'];
        $manage_id      = $post['manage_id'];

        if($check_status == 1){
            $sent_info      = $post['sent_info'];
            $sent_info     += [
                'ip_address' => ip(),
                'account_holder_group_token' => getSetting("business_group_token")
            ];
            $list           = $this->find($check_id);
            $username       = $list['username'];
            $businessApi = apiIndex::requestApi('create_business_user' , $sent_info);
            if($businessApi){
                $blog = $this->update(
                    ['check_status' => 1 ,'business_token'    => $businessApi['token']],
                    ['id' => $check_id]);
                ManageLog::saveManageLog([
                    'manage_id' => $manage_id,
                    'desc'      => 'business info send',
                    'content'   => ['email' => $username]
                ]);
            }else{
                //2=信息发送失败
                $blog = $this->update(
                    ['check_status' => 2 ,'business_token'    => $businessApi['token'] ?? ''],
                    ['id' => $check_id]);
            }

        }else{
            //2=信息不允许发送
            $blog = $this->update(['check_status' => 2 ,'reply_msg' => 'The administrator information is not sent'] , ['id' => $check_id]);
        }
        return $blog;
    }

    public function activeBusiness($data)
    {
        $check_id       = $data['id'];
        $manage_id      = $data['manage_id'];
        $user_type      = $data['user_type'] ?? 0;

        $list           = $this->find($check_id);
        $username       = $list['username'];
        $user_list      = Db::name('user')->where(['username' => $username])->find();
        if(!$user_list){
            $create_user_data = [
                'user_num'      => $list['user_num'],
                'username'      => $username,
                'password'      => $list['password'],
                'ctime'         => $list['ctime'],
                'check_time'    => getUtcTime(), //计费开始的审核时间,
                'user_type'     => $user_type,
                'business_token'=> $list['business_token']
            ];
            //$user_type 1=共享模式，0=单卡模式
            // 如果是共享模式 开卡金额无意义,开卡上限是10，后续管理员调整
            if($user_type == 1){
                $create_user_data += [
                    'card_max'    => 10
                ];
            }
            $re = Db::name('user')->save($create_user_data);
            $this->update(['check_result' => 1] , ['id' => $check_id]);
            //发送邮件通知激活了
            EmailSend::sendEmail('account_notice' , [
                'email'     => $username ,
                'desc'      => "account_notice"
            ]);
            ManageLog::saveManageLog([
                'manage_id' =>$manage_id,
                'desc'      => 'business Active',
                'content'   => ['email' => $username , 'user_type' => ($user_type == 1)?'Share':'Single']
            ]);
        }else{
            $re = false;
        }

        return $re;
    }

    public static function sentKyc($data){
        $check_id       = $data['id'];
        $manage_id      = $data['manage_id'];
        $list           = Db::name("user_check")->where(['id' => $check_id])->find();
        $business_token = $list['business_token'];
        $username       = $list['username'];
        $businessApi = apiIndex::requestApi('sent_kyc' , ['business_token' => $business_token]);
        if($businessApi){
            $re      = Db::name("user_check")->where(['id' => $check_id])->update(["check_kyc"=>1]);
        }else{
            $re = false;
        }

        ManageLog::saveManageLog([
            'manage_id' => $manage_id,
            'desc'      => "{$username} kyc sent",
            'content'   => ['email' => $username]
        ]);
        return $re;
    }

    public static function changeKyc($data){
        $check_id       = $data['id'];
        $manage_id      = $data['manage_id'];
        $list           = Db::name("user_check")->where(['id' => $check_id])->find();
        $username       = $list['username'];
        $re             = Db::name("user_check")->where(['id' => $check_id])->update(["check_kyc"=>2]);

        ManageLog::saveManageLog([
            'manage_id' => $manage_id,
            'desc'      => "{$username} kyc passed",
            'content'   => ['email' => $username]
        ]);
        return $re;
    }

    public static function createUsers()
    {
//        $list = Db::name('user_check')->where(['id' => 1])->find();
//        unset($list['id']);
//        for($i=10;$i<50;$i++){
//            $user_num         = getRandNumber();
//            $list['user_num'] = $user_num;
//            $username         = "sensir" . (100 + $i) . "@gmail.com";
//            $list['username'] = $username;
//            Db::name('user_check')->save($list);
//
//            $userApi = apiIndex::requestApi('create_user' , ['first_name' => $username]);
//
//            Db::name('user')->save([
//                'user_num' => $user_num,
//                'username' => $username,
//                'password' => $list['password'],
//                'ctime'    => $list['ctime'],
//                'user_token'=> $userApi['token']
//            ]);
//        }
//        echo 'ok';
    }

    public function getUserDetail($user_num)
    {
        $user_check_list = $this
            ->field('business_address,business_apartment,business_city,business_state,business_zip')
            ->where(['user_num' => $user_num])->find();
        return $user_check_list;
    }


    public function tableDataVeriff($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        if(isset($post['username']) && !empty($post['username'])){
            $where[] = ['u.username', 'like', '%'.$post['username'].'%'];
        }
        if(isset($post['session_id']) && !empty($post['session_id'])){
            $where[] = ['session_id', 'like', '%'.$post['session_id'].'%'];
        }

        $list = Db::name('user_veriff')->alias('c')
            ->leftJoin('user u' ,'u.id=c.user_id')
            ->field('c.*,u.username')
            ->where($where)
            ->order('time desc')
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();

        return [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

}